// pages/result/result.js
import request from '../../utils/request'
import api from "../../config/api";
import { shareOptions } from '../../utils/access';
import { getStorage, removeStorage, formatDuring } from "../../utils/utils"
const { getBarAndTitleHeight, getXsScreen, stringify, parse, jump, goBack } = require("../../utils/utils.js");
const app = getApp()
// 引入动画插件
import lottie from './lottie'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 状态栏&标题栏高度
    ...getBarAndTitleHeight(true),
    // 页面是否可以加载
    isReady: false,
    // 是否是任务
    isTask: false,
    // 任务是否成功
    isSuccess: true,
    // 是否是今日
    isToday: true,
    // 详情信息
    detailData: {},
    // 统计信息
    totalData: {
      total: 0,
      right: 0,
      percent: 0
    },
    // 类型图片列表
		iconList: [
      '',
			// 学习
			"https://image-classify.daieco.com/kejian-space/V49nBESzwfPvfdc6a055c8ee133bb50947fd736436a8.png",
			// 厨余垃圾
      "https://image-classify.daieco.com/kejian-space/zna866jbDKkw266093b9bcd98f5f15aa5b6e44ad4c61.png",
      // 可回收垃圾
      "https://image-classify.daieco.com/kejian-space/6RkmjUa2pLl76b668c7aadef51ba88fee1105a75ea35.png",
      // 有害垃圾
			"https://image-classify.daieco.com/kejian-space/KkTY9FwDUshQ15f9e3e518b6349d2b4b1c447019158e.png",
			// 其他垃圾
			"https://image-classify.daieco.com/kejian-space/tqId1U1LRu2N97938b1969cdfeb707ef14f20e3b77be.png",
		],
    // 学习内容列表
    learnList: [],
    // 答题详情列表
    answerList: [],
    // 答题详情列表原始
    answerOriginList: [],
    // 题目过滤类型 0 全部 1 只看对的 2 只看错的 3 我放弃的
    questionFilter: 0,
    // 任务id
    taskId: null,
    // 是否是洼刘社区
    isTestCommunity: false,
    // 奖品名称
    drawName: '',
    // 24小时内是否已经分享成功过
    count: 0,
    // 24小时内答题获奖次数
    drawCount: 0,
    // 是否从PK活动进入
    fromActivity: false,
    // 是否展示动画
    showAnimation: true,
    // 动画距离顶部距离
    successTop: 0,
    // 是否是小屏幕尺寸
		...getXsScreen(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let detail
    let result
    if (options.detail) {
      try {
        detail = parse(options.detail)
      } catch { }
    }
    if (options.result) {
      try {
        result = parse(options.result)
        console.log('result',result);
      } catch { }
    }

    // 上报分数数据
    wx.reportAnalytics?.('score_record', {
      userid: app?.globalData?.userId,
      openid: app?.globalData?.swapData?.openid,
      score: Number(result?.accuracy || 0),
      prize: result?.prizeName,
      is_test: Number(options?.isTest || 0),
      platform: app?.globalData?.systemInfo?.platform,
    })
  
    this.setData({
      ...getBarAndTitleHeight(),
      isTest: Number(options.isTest),
      isTask: Number(options.taskId) !== 0,
      taskId: options.taskId,
      percent: Number(result?.accuracy || 0),
      drawName: result?.prizeName?.replace('兑换券', ''),
      fromActivity: Number(getStorage('fromActivity')) === 1
    });

    // 判断是否是洼刘小区用户
    // this.checkWaliu()

    if (Number(options.taskId) !== 0) {
      this.getLearnList(options.taskId)
    }
    if (result) {
      this.update(result, detail)

      // 答题抽奖
      this.checkIsTarget()
    } else {
      this.getData(options.taskId)
    }

    const query = wx.createSelectorQuery();
    query.select('.successCanvas').boundingClientRect();
    query.exec((res) => {
      if(res[0]){
        console.log(res); //这个节点距离顶部的距离   和距离底部的距离
        let menutop = res[0].top;
        this.setData({
          successTop: res[0].top
        })
      }
    })

    // 初始化动画
    this.init()
  },
  /**
   * 初始化加载动画
   */
  init() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#success-canvas')
      .node((res) => {
        if(res[0]){
          const canvas = res[0].node
          const context = canvas.getContext('2d')
          canvas.width = 300
          canvas.height = 300
          lottie.setup(canvas)
          this.ani = lottie.loadAnimation({
            loop: false,
            autoplay: true,
            animationData: require('./data.js'),
            rendererSettings: {
              context,
            },
          })
          this.inited = true
        }
      })
      .exec()
  },

  /**
   * 更新数据
   * @param {*} result 
   * @param {*} detail 
   */
  update(result, detail) {
    // 答题详情
    const {isTask} = this.data
    const giveupNum = (result?.answerDetailVOList || []).filter(item => !item.yourOption).length
    let totalData = {
      total: result?.rightNum + result?.wrongNum,
      right: result?.rightNum,
      wrong: result?.wrongNum - giveupNum,
      giveup: giveupNum,
      percent: Number(result?.accuracy || 0)
    }
    let detailData = {
      month: '',
      day: '',
    }
    if (result?.taskDate) {
      const taskDate = new Date(result.taskDate)
      const day = taskDate.getDate()
      const month = taskDate.getMonth() + 1

      const date = new Date()
      const nowMonth = date.getMonth() + 1
      const nowDay = date.getDate()
      this.setData({
        isToday: day == nowDay && month == nowMonth
      })
      detailData = { day, month }
    }
    // 每日一答  用时格式转换
    if(this.data.isTest === 1){
      if(result.useTime){
        let timeObj = formatDuring(result.useTime)
        result.useTimes =`${timeObj.minutes}:${timeObj.seconds}`
      }else{
        result.useTimes='-'
      }
    }
    this.setData({
      detail,
      result,
      isSuccess: result?.isSuccess == 1,
      totalData,
      isReady: true,
      answerList: result?.answerDetailVOList,
      answerOriginList: result?.answerDetailVOList?.map((item) => ({
        ...item,
        questionType: item.yourOption === item.rightOption ? 1 : (item.yourOption ? 2 : 3)
      })),
      detailData
    });
    
  },

  //获取学习列表
  async getLearnList(taskId) {
    const res = await request.post(`${api.getResultTaskList + '/'}${taskId}`)
    console.log('res', res);
    this.setData({
      learnList: res?.data
    })
  },

  // 获取详情数据
  async getData(taskId) {
    const res = await request.get(api.getResult, { taskId })
    this.update(res?.data)
  },

  // 再去看看
  toArticlePage() {
    wx.navigateBack({
      delta: 1,
    })
  },

  back() {
    const pages = getCurrentPages()
		if (pages.length > 1) {
			wx.navigateBack({
				delta: 1,
			})
		} else {
			jump('index')
		}
  },
  // 判断是否是洼刘小区
  async checkWaliu(){
    if (!app.isLogin()) return
    const res = await request.get(api.isWaliu, {}, { loading: false, modal: false })
    // const res = {
    //   httpStatus: 200,
    //   data: false
    // }
    this.setData({
      isTestCommunity: res?.data
    })
    // 是洼刘小区并且从首页“测试“进入并且80分以上自动抽奖
    if(res?.data && this.data.isTest === 1) {
      if (this.data.percent >= 80 && this.data.drawName) {
        console.log('this.data.drawName',this.data.drawName);
        if (this.lotteryModal) {
          this.lotteryModal.show()
        } else {
          this.showLotteryModal = true
        }
      }
      this.getDrawCount()
      // this.getShareCount()
    }
  },

  // 判断是否是目标小区用户
  async checkIsTarget(){
    if (!app.isLogin()) return
    const res = await request.get(api.isTargetCommunity, {}, { loading: false, modal: false })
    this.setData({
      isTestCommunity: res?.data
    })
    // 是目标小区并且从首页“测试“进入并且80分以上自动抽奖
    if(res?.data && this.data.isTest === 1) {
      if (this.data.percent >= 80 && this.data.drawName) {
        console.log('this.data.drawName',this.data.drawName);
        if(this.data.drawName==='谢谢参与'){
          if(this.lostPrizeModal){
            this.lostPrizeModal.show()
          }else{
            this.showLostPrizeModal = true
          }
        }else{
          if (this.lotteryModal) {
            this.lotteryModal.show()
          } else {
            this.showLotteryModal = true
          }
        }
      }
      this.getDrawCount()
    }
  },
  // 获取24小时内答题获奖次数
  async getDrawCount(){
    if (!app.isLogin()) return
    let that = this
    // shareType: 分享类型 1答题分享
    const res = await request.get(api.getDrawCount,{ source: 9 }, { loading: false, modal: false }) 
    if(res?.data){
      that.setData({
        drawCount: res.data
      })
    }
  },
  // 获取24小时内分享次数
  async getShareCount(){
    if (!app.isLogin()) return
    let that = this
    // shareType: 分享类型 1答题分享
    const res = await request.get(api.getShareCount,{shareType: 1}, { modal: false }) 
    if(res?.data){
      that.setData({
        count: res.data
      })
    }
  },

  /**
   * 跳转文章详情页面
   */
  jumpDetail(e) {
    const { item = {} } = e.currentTarget.dataset || {}
    wx.navigateTo({
      url: `/pages/detail/detail?id=${item.id}`,
    })
  },

  /**
   * 跳转首页
   */
  jumpIndex() {
    jump('index')
  },

  /**
   * 返回答题页面或跳转我的挑战
   */
  async jumpPage() {
    const { detail, isTask, isSuccess, isTest, taskId } = this.data
    if (isTask && isSuccess) {
      wx.navigateTo({
        url: '/pages/trophy/trophy',
      })
    } else {
      if (taskId !== '0' && taskId) {
        wx.redirectTo({
					url: `/pages/answer/answer?id=${detail?.id}&taskId=${taskId}`,
				});
      } else {
        if (isTest) {
          wx.redirectTo({
            url: `/pages/answer/answer?isTest=1`,
          })
        } else {
          wx.redirectTo({
            url: `/pages/answer/answer?isTest=${isTest}&id=${detail.id}&taskId=${taskId}&detail=${stringify(detail)}&question=${stringify(detail.questionData)}`,
          })
        }
      }
    }
  },
  // 跳转圈子页面
  jumpCircle() {
    this.modal.hide()
    jump('circle', { id: 1 })
  },
  //完成任务发布动态
  async publishDynamic(){
    if (this.loading) return
    this.loading = true
    const res = await request.get(api.getCircleListAdded, null, { loading: false })

    // 是否有加入的圈子
    if (res?.data?.length) {
      wx.navigateTo({
        url: '/pages/publish/publish?task=3',
      })
    } else {
      this.modal.show()
    }
    this.loading = false
  },
  // 关闭奖品弹窗
  lotteryModalClose: function () {
    this.lotteryModal.hide();
    this.lostPrizeModal.hide();
  },
  // 跳转兑换券列表
  goReward(){
    jump('coinCertificate');
    this.lotteryModal.hide()
  },
  // 分享插入记录
  async getShareDraw(){
    const res = await request.get(api.saveShareLog, { shareType: 1 }, { loading: false, modal: false })
    if (res?.data) {
      // 分享成功后抽奖
      // this.toShareDraw()
    }
  },
  // 分享成功后抽奖
  async toShareDraw(){
    if (!app.isLogin()) return
    const res = await request.get(api.answerShareDraw, null, { loading: false, modal: false })
    if (res?.data) {
      this.setData({
        drawName: res?.data.replace('兑换券', '')
      })
      this.lotteryModal.show()
      // 重新获取分享次数
      this.getShareCount()
    }
  },
  // 用户点击右上角分享
	onShareAppMessage(e) {
    let { totalData, isTest } = this.data
    const userId = getStorage('userId') || ''
    // 从首页“测试”入口
    if(isTest === 1){
      // 只要登录就调 分享获得一次随机礼物 接口
      if(app.isLogin()){
        // 自动获得奖品
        this.getShareDraw()
      }
      // let title = `我答了${totalData.percent}分，你能答多少分?`  //'全国垃圾分类答题测试'
      // let path = '/pages/test/test?inviteData=' + getStorage('userId')
      // return shareOptions('default', e, title, path, null)
      return shareOptions('default', e, '全国垃圾分类答题测试', `/pages/answerHome/answerHome?inviteData=${userId}`, 'https://image-classify.daieco.com/kejian-quanzi/TlHkdrPLJ0dd1a05ff9659bbd2311b67642b30830074.png')
    }else{
      return shareOptions('test', e)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
    this.lotteryModal = this.selectComponent('#lotteryModal');
    this.lostPrizeModal = this.selectComponent('#lostPrizeModal');
    this.filterSheet = this.selectComponent('#filterSheet');

    if(this.showLostPrizeModal){
      this.showLostPrizeModal = false
      this.lostPrizeModal.show()
    }
    if (this.showLotteryModal) {
      this.showLotteryModal = false
      this.lotteryModal.show()
    }
  },
  // 更改题目类型
  changeQuestionFilter(event) {
    const { answerOriginList } = this.data
    const questionFilter = event.currentTarget.dataset.type
    this.setData({
      questionFilter,
      answerList: answerOriginList?.filter(item => questionFilter ? item.questionType === questionFilter : true)
    })
    this.hideFilter()
  },
  // 显示题目类型过滤弹窗
  showFilter() {
    this.filterSheet.show()
  },
  // 隐藏题目类型过滤弹窗
  hideFilter() {
    this.filterSheet.hide()
  },
  // 返回活动
  handleActivity(){
    goBack(2)
    removeStorage('fromActivity')
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onPageScroll(e) {
    let { successTop } = this.data
    if (e.scrollTop >  successTop-91) {
      this.setData({
        showAnimation: false
      })
    }
  },
})

